<template>
	<rui-pages>
		<rui-circle>
			<view v-for="(item, index) in product_list" :key="index">
				<rui-search-device :data="item"></rui-search-device>
			</view>
		</rui-circle>
	</rui-pages>
</template>

<script setup>
	import {
		ref
	} from "vue"
	import {
		onLoad,
		onUnload,
		onShow
	} from "@dcloudio/uni-app"
	import {
		getSearchProduct,
		getAllDevice
	} from "@/common/api.js"

	import {
		userStore
	} from "@/store"
	import ble from "@/util/ble"
	import {
		parseMacFromAdvertisData
	} from "@/util/common.js"

	let user = userStore();
	let devices = [];
	let product_list = ref([]);

	onLoad(() => {
		//获取设备列表
		getAllDevice().then(res => {
			devices = res.data;
			console.log(devices)
			//开始搜索
			ble.start(() => {
				search()
			})
		})
	})

	onShow(() => {
		search()
	})

	//监听搜索蓝牙设备
	ble.watch = (event, device) => {
		console.log(event, device)
		if (event == 'search') {
			getProduct(device)
		}
	}
	
	const search = () => {
		ble.search(device => {
			for (let key in device) {
				if (device[key].name) {
					getProduct(device[key])
				}
			}
		})
	}

	const getProduct = (device) => {
		// console.log(111111111, device)
		if (devices.includes(device.name)) {
			//判断数组中是否有重复对象
			let device_id = parseMacFromAdvertisData(device.advertisData)
			//获取新发现产品
			getSearchProduct({
				name: device.name,
				device_id
			}).then(res => {
				if (res.data.id) {
					if (!product_list.value.some(obj => obj.device_id == device_id)) {
						res.data.device_id = device_id
						res.data.mac = device.deviceId
						product_list.value.push(res.data);
						console.log(22222222, product_list.value)
					}
				}
			})
		}
	}



	onUnload(() => {
		//停止搜索
		ble.stop()
		//销毁监听
		ble.watch = function() {};
	})
</script>

<style lang="scss" scoped>

</style>